package com.glaway.car.interceptor;

import com.glaway.car.context.BaseContext;
import com.glaway.car.entity.Admin;
import com.glaway.car.properties.JwtProperties;
import com.glaway.car.utils.JwtUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的令牌（token）。
        String jwt = request.getHeader(jwtProperties.getTokenName());

        // 判断令牌是否存在，如果不存在，返回错误结果（未登录）。
        if(!StringUtils.hasLength(jwt)){ //jwt为空
            log.info("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            Claims claims = JwtUtils.parseJWT(jwt, jwtProperties.getSecretKey());
            Admin admin = new Admin(
                    claims.get("id").toString(),
                    Integer.valueOf(claims.get("permission").toString()),
                    claims.get("username").toString(),
                    null
                            );
            log.info("当前用户："+ admin);
            BaseContext.setCurrentAdmin(admin);
        } catch (Exception e) {
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 放行。
        log.info("令牌合法, 放行");
        return true;

    }
}
